package cn.melonlib.apis.http.comp.action;

import cn.melonlib.apis.http.enums.RequestMethod;
import cn.melonlib.apis.http.enums.ResponseStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.function.Consumer;

@Component
public class RestRequestAction {

    @Resource
    private OkHttpClient okHttpClient;

    @Resource
    private ObjectMapper jsonMapper;

    public RestResponseInfo request(
            String url,
            RequestMethod method,
            Map<String,Object> params,
            Map<String,String> headers,
            Consumer<Response> callResponse
    ) throws Exception{
        long startTime=System.currentTimeMillis();
        Request request= switch (method){
            case JSON -> {
                MediaType mediaType=MediaType.parse("application/json;charset=UTF-8");
                RequestBody requestBody=RequestBody.create(jsonMapper.writeValueAsBytes(params),mediaType);
                yield new Request.Builder().url(url).post(requestBody).headers(headers.entrySet().stream().reduce(new Headers.Builder(),(h, m)->h.add(m.getKey(),m.getValue()),(h, m)->null)
                        .build()).build();
            }
            default -> new Request.Builder().url(url).headers(headers.entrySet().stream().reduce(new Headers.Builder(),(h, m)->h.add(m.getKey(),m.getValue()),(h, m)->null)
                    .build()).get().build();
        };

        try(Response response=okHttpClient.newCall(request).execute()){
            System.out.println(response.body().contentType().type());
            callResponse.accept(response);
            long responseTime=System.currentTimeMillis();
            return new RestResponseInfo(response.code(),  response.body().contentType().toString(), response.body().contentLength(),startTime,responseTime, ResponseStatus.SUCCESS);
        }
    }

}
